package com.flats.model.dao.hibernate;

import com.flats.model.entity.Comment;
import com.flats.model.entity.Persistent;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Transactional
public class CommentHibernateDao<T extends Persistent> extends AbstractHibernateDao<Comment> {
    @Override
    @Transactional
    public Serializable saveOrUpdate(Comment persistent) {
        if (getSession().getTransaction()!=null && !getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        System.out.println("persistent.getDate() = " + persistent.getDate());
        System.out.println("persistent.getUser().getName() = " + persistent.getUser().getName());
        System.out.println("persistent.getFlat().getId() = " + persistent.getFlat().getId());
        Serializable id = getSession().save(persistent);
        getSession().getTransaction().commit();
        return id;
    }

    @Override
    @Transactional
    public void delete(Long id) {

    }

    @Override
    @Transactional
    public void delete(Comment persistent) {
        getSession().beginTransaction();
        getSession().delete(persistent);
        getSession().getTransaction().commit();
    }

    @Override
    @Transactional
    public Comment get(Long id) {
        if (getSession().getTransaction()!=null && !getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        Comment result = (Comment) getSession().load(Comment.class, id);
        return result;
    }

    @Override
    @Transactional
    public List<Comment> getAll() {
        if (getSession().getTransaction()!=null && !getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        String query = "select * from ROOT_USER.Comment";
        List<Comment> commentList = getSession().createSQLQuery(query)
                .addEntity(Comment.class)
                .list();
        return commentList;
    }
}
